<template>
  <div class="side-bar" ref="side">
    <div
      class="item"
      :class="{ active: index === i }"
      v-for="(item, i) in sideBar"
      :key="item.title"
      @touchend="scrollTo(i, $event)"
      @touchstart="move = false"
      @touchmove="move = true"
    >
      {{ i === 0 ? "全部" : item }}
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import moveTo from '@/utils/moveToMiddle';

export default {
  data() {
    return {
      index: 0,
      move: false, // 是否正在移动
    };
  },
  computed: {
    ...mapState(['sideBar', 'size']),
  },
  methods: {
    ...mapMutations(['resetGoodsList']),
    scrollTo(i, e) {
      if (this.move) {
        return;
      }
      this.index = i;
      const parTop = this.$refs.side.getBoundingClientRect().top;
      const parHeight = this.$refs.side.offsetHeight / 2;
      const sonTop = e.target.getBoundingClientRect().top;
      const sonHeight = e.target.offsetHeight / 2;
      //   this.$refs.side.scrollTop += sonTop + sonHeight - parTop - parHeight;
      moveTo(
        this.$refs.side.scrollTop,
        sonTop + sonHeight - parTop - parHeight,
        this.$refs.side,
        'scrollTop',
      );
      this.resetGoodsList();
      this.$store.dispatch('setGoodsList', {
        type: this.sideBar[i],
        page: 1,
        sort: 'all',
      });
    },
  },
  mounted() {
    this.resetGoodsList();
    this.$store.dispatch('setGoodsList', {
      type: this.sideBar[0],
      page: 1,
      sort: 'all',
    });
  },
};
</script>

<style lang="less" scoped>
.side-bar {
  position: fixed;
  row-gap: 135px;
  left: 0px;
  width: 79px;
  top: 145px;
  bottom: 50px;
  overflow: auto;
  background: #f8f8f8;
  &::-webkit-scrollbar {
    width: 0;
    background: none;
  }
  .item {
    width: 79px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    position: relative;
    &.active {
      font-weight: bold;
      color: #ff1a90;
      &::before {
        position: absolute;
        width: 6px;
        height: 18px;
        background: #ff1a90;
        top: 50%;
        left: 0;
        transform: translateY(-50%);
        content: "";
      }
    }
  }
}
</style>
